<template>
    <div>
        <v-back/>
        <div class="myHeader">
            <div class="headerUri">
                <div class="headerImg" @click="showCamPhoto = true">
                    <img :src="userInfo.headImage.includes('http')? userInfo.headImage : showImg(userInfo.headImage)" alt="">
                </div>
                <span class="userIcon">
                    <img src="~@/assets/images/icon_photo.png">
                </span>
            </div>
        </div>
        <van-cell-group>
            <changeCell label="昵称" :value="userInfo.nickname" @changeBtn="changeName"/>
            <changeCell label="性别" :value="userInfo.sex == 1 ? '男': userInfo.sex == 2?'女': '未知'"
                        @changeBtn="changeSex"/>
            <changeCell label="所在地" :value="userInfo.city" @changeBtn="showArea = true"/>
            <changeCell label="手机号" :value="hidePhone(userInfo.phone)" @changeBtn="goSetTel()"/>
        </van-cell-group>


        <!--        性别改变框-->
        <van-action-sheet
                v-model="sheetData.show"
                :actions="sheetData.actions"
                cancel-text="取消"
                close-on-click-action
                @select="onSexSelect"
        />

        <!--        照相选择-->
        <van-popup
                v-model="showCamPhoto"
                position="bottom">
            <div class="popUp-title">
                <span>更改头像</span>
                <van-icon class="closeBtn" @click="showCamPhoto=false" name="cross" size="20" color="#c8c9cc"/>
            </div>
            <div class="cameraAndPhoto">
                <div @click="chooseImg('album')">
                    <img src="~@/assets/images/photo.png">
                    <span>本地相册</span>
                </div>
                <div @click="chooseImg('camera')">
                    <img src="~@/assets/images/camera.png">
                    <span>手机拍照</span>
                </div>
            </div>
        </van-popup>
        <v-address :show="showArea" @cancel="cancel" @confirm="confirm"></v-address>
    </div>
</template>

<script>
    import {mapGetters, mapMutations} from 'vuex'
    import {ActionSheet} from 'vant'
    import changeCell from '../../../components/changeCell';
    import wxValidate from '@/config/wx.validate'
    import vAddress from '@/components/address'
    export default {
        name: "index",
        mixins: [wxValidate],
        components: {changeCell, 'van-action-sheet': ActionSheet,vAddress},
        computed: {...mapGetters(['userInfo'])},
        data() {
            return {
                showArea: false,
                areaList: areaList,
                name: '张三',
                sex: '男',
                address: '成都',
                tel: '13800138000',
                sheetData: {
                    show: false,
                    actions: [{name: '未知', id: 0}, {name: '男', id: 1}, {name: '女', id: 2}]
                },
                showCamPhoto: false,
                wxReady: false
            }
        },
        mounted() {
            // this.wxSignature();
        },
        methods: {
            ...mapMutations(['SET_USERINFO']),
            changeName() {
                this.$alert(
                    {
                        title: '修改昵称',
                        type: 'prompt',
                        hint: '请输入新的昵称',
                        content: '内容',
                        showCancel: true,
                        cancelText: '取消'
                    }
                ).then(async (val) => {
                    this.changeUserDetail({nickname: val});
                }).catch(_ => {
                    console.log('取消');
                });
            },


            //修改用户信息
            async changeUserDetail(obj) {
                const {errorCode, data} = await this.$http.put('/mp/user/info', obj);
                if (errorCode !== '00000') return;

                localStorage.setItem('userinfo', JSON.stringify(data));
                this.SET_USERINFO(data);
            },

            //base64转文件
            convertBase64UrlToBlob(b64Data,sliceSize) {
                let arr = b64Data.split(',');
                let mime = arr[0].match(/:(.*?);/)[1];


                sliceSize = sliceSize || 512;

                let byteCharacters = atob(b64Data.substring(b64Data.indexOf(',') + 1));
                let byteArrays = [];
                for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                    let slice = byteCharacters.slice(offset, offset + sliceSize);
                    let byteNumbers = new Array(slice.length);
                    for (let i = 0; i < slice.length; i++) {
                        byteNumbers[i] = slice.charCodeAt(i);
                    }

                    let byteArray = new Uint8Array(byteNumbers);
                    byteArrays.push(byteArray);
                }

                return new Blob(byteArrays, {type: mime});


            },


                //选择相片
            async chooseImg(type) {
                this.showCamPhoto = false;

                const fileBase64 = await this.chooseImage(type);
                let params = new FormData();
                params.append('files', this.convertBase64UrlToBlob(fileBase64));
                this.$loading();
                try {
                    let fileRes = await this.$http.post('/mp/upload/file/other', params, {headers: {'Content-Type': 'multipart/form-data'}});
                    await this.changeUserDetail({headImage: fileRes.data[0].url});
                }catch (e) {

                }finally {
                    this.$loading.close();
                }

            },


            changeSex() {
                this.sheetData.show = true;

            },
            onSexSelect(val) {
                console.log(val);
                this.changeUserDetail({sex: val.id});
            },
            goSetTel() {
                this.$router.push('/validate');
            },

            cancel() {
                this.showArea = false;
            },

            async confirm(area) {
                console.log(area);
                await this.changeUserDetail({pccProvinceId: area[0].id,pccCityId: area[1].id,pccCountryId: area[2].id,city: area[1].name});
                this.showArea = false;
            },
        }
    }
</script>

<style lang="less" scoped>
    .myHeader {
        height: 1.36rem;
        background-color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        .headerUri {
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            position: relative;

            .headerImg {
                width: .96rem;
                height: .96rem;
                border-radius: 50%;
                overflow: hidden;
                img {
                    width: 100%;
                }
            }

            .userIcon {
                position: absolute;
                bottom: 0;
                right: 0;
                img {
                    width: .25rem;
                }
            }
        }
    }

    .popUp-title {
        padding: 16px 0;
        font-size: 15px;
        text-align: center;
        position: relative;
    }

    .closeBtn {
        position: absolute;
        top: 17px;
        right: 16px;
    }

    .cameraAndPhoto {
        display: flex;
        flex-direction: row;
        & > div {
            cursor: pointer;
            display: flex;
            flex: 1;
            height: 150px;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            img {
                width: 40px;
                height: 40px;
            }
            span {
                font-size: 14px;
                margin-top: 20px;
            }
        }
    }
</style>
